/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: TokenListActivity.java
 *   @Date: 19-4-28 下午2:53
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.market.ui;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.Collections;
import java.util.List;

import cn.bingoogolapple.baseadapter.BGABaseAdapterUtil;
import cn.bingoogolapple.baseadapter.BGADivider;
import cn.bingoogolapple.baseadapter.BGARVVerticalScrollHelper;
import io.bhex.app.R;
import io.bhex.app.account.ui.AssetDetailActivity;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.market.presenter.TokenListPresenter;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.KeyBoardUtil;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.index.CharacterParser;
import io.bhex.app.view.index.IndexView;
import io.bhex.app.view.index.PinyinComparator;
import io.bhex.app.view.index.adapter.RecyclerIndexAdapter;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.sdk.account.bean.enums.VERIFY_STATUS;
import io.bhex.sdk.quote.bean.QuoteTokensBean;

public class TokenListActivity extends BaseActivity<TokenListPresenter, TokenListPresenter.TokenListUI> implements TokenListPresenter.TokenListUI, View.OnClickListener, TextWatcher{
    private RecyclerIndexAdapter mAdapter;
    private BGARVVerticalScrollHelper mRecyclerViewScrollHelper;
    private IndexView indexView;
    private boolean isDeposit;
    private TextView indexViewTipsTv;
    private boolean bindGA;
    private boolean isBindMobile;
    private boolean isBindEmail;
    private boolean isVerify;
    private boolean bindTradePwd;

    @Override
    protected int getContentView() {
        return R.layout.activity_token_list_layout;
    }

    @Override
    protected TokenListPresenter createPresenter() {
        return new TokenListPresenter();
    }

    @Override
    protected TokenListPresenter.TokenListUI getUI() {
        return this;
    }

    private RecyclerView recyclerView;
    private View emptyView;

    @Override
    protected void initView() {
        super.initView();
        Intent intent = getIntent();
        if (intent != null) {
            isDeposit = intent.getBooleanExtra("isDeposit", true);
        }
        FrameLayout framLayout = viewFinder.find(R.id.framLayout);
        recyclerView = viewFinder.find(R.id.recyclerView);
        indexView = viewFinder.find(R.id.indexview);
        indexViewTipsTv = viewFinder.textView(R.id.indexview_tip_tv);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        emptyView = layoutInflater.inflate(R.layout.empty_layout, framLayout, false);

        indexView.setBackgroundColor(SkinColorUtil.getDark10(this));
        indexView.setTipTv(indexViewTipsTv);
        initUserInfoConfig();
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.search_cancel).setOnClickListener(this);
        viewFinder.editText(R.id.search_edit).addTextChangedListener(this);
        findViewById(R.id.input_clear).setOnClickListener(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPresenter().getUserInfo();
    }

    @Override
    public void showUserInfo(UserInfoBean data) {
        initUserInfoConfig();
    }

    private void initUserInfoConfig() {
        UserInfoBean userInfo = UserInfo.getUserInfo();
        if (userInfo != null) {
            bindTradePwd = userInfo.isBindTradePwd();
            bindGA = userInfo.isBindGA();
            String mobile = userInfo.getMobile();
            String email = userInfo.getEmail();
//            isBindMobile = !TextUtils.isEmpty(mobile) && userInfo.getRegisterType() != 1;
//            isBindEmail = !TextUtils.isEmpty(email) && userInfo.getRegisterType() != 2;
            isBindMobile = !TextUtils.isEmpty(mobile);
            isBindEmail = !TextUtils.isEmpty(email);
            int verifyStatus = userInfo.getVerifyStatus();
            if (verifyStatus==VERIFY_STATUS.VERIFY_CHECKED.getmStatus()) {
                isVerify = true;
            }
        }
    }

    @Override
    public void showTokenList(List<QuoteTokensBean.TokenItem> datas) {
        if (datas != null) {
            //数据处理：首字母 排序处理
            PinyinComparator pinyinComparator = new PinyinComparator();
            CharacterParser characterParser = CharacterParser.getInstance();
            for (QuoteTokensBean.TokenItem item : datas) {
                item.setFirstLetter(characterParser.getSelling(item.getTokenName()).substring(0, 1).toUpperCase());
            }
            Collections.sort(datas, pinyinComparator);
        }
        if (mAdapter == null) {
            mAdapter = new RecyclerIndexAdapter(datas);
            mAdapter.setEmptyView(emptyView);
            mAdapter.isFirstOnly(false);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(mAdapter);

            mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    List<QuoteTokensBean.TokenItem> data = adapter.getData();
                    if (data != null) {
                        QuoteTokensBean.TokenItem tokenItem = data.get(position);
                        if (tokenItem != null) {
//                            ToastUtils.showShort(tokenItem.getTokenId() + "  " + isDeposit);
                            if (isDeposit) {
                                //充币
                                if (tokenItem.isAllowDeposit()) {
                                    IntentUtils.goMyAssetTokenDeposit(tokenItem.getTokenId(),TokenListActivity.this);
                                    finish();
                                }else{
                                    ToastUtils.showShort(TokenListActivity.this, tokenItem.getTokenName()+" "+getString(R.string.string_suspeng_deposit));
                                }
                            } else {
                                if (!isFinishing()) {
                                    //提币
                                    if (tokenItem.isAllowWithdraw()) {
                                        IntentUtils.goMyAssetTokenWithdraw(tokenItem.getTokenId(),TokenListActivity.this);
                                        finish();
                                    } else {
                                        ToastUtils.showShort(TokenListActivity.this, tokenItem.getTokenName()+" "+getString(R.string.string_suspeng_withdraw));
                                    }
                                }
                            }
                        }
                    }
                }
            });
            final BGADivider.StickyDelegate stickyDelegate = new BGADivider.StickyDelegate() {

                @Override
                protected void initAttr() {
                    super.initAttr();
                    mCategoryBackgroundColor = SkinColorUtil.getDark20(TokenListActivity.this);
                    mCategoryTextColor = getResources().getColor(R.color.grey);
                }

                @Override
                protected boolean isCategoryFistItem(int position) {
                    return mAdapter.isCategory(position);
                }

                @Override
                protected String getCategoryName(int position) {
                    return mAdapter.getItem(position).getFirstLetter();
                }

                @Override
                protected int getFirstVisibleItemPosition() {
                    return mRecyclerViewScrollHelper.findFirstVisibleItemPosition();
                }
            };

            recyclerView.addItemDecoration(BGADivider.newBitmapDivider()
                    .setStartSkipCount(0)
                    .setMarginLeftResource(R.dimen.app_margin_left)
                    .setMarginRightResource(R.dimen.app_margin_right)
                    .setDelegate(stickyDelegate));
            mRecyclerViewScrollHelper = BGARVVerticalScrollHelper.newInstance(recyclerView, new BGARVVerticalScrollHelper.SimpleDelegate() {
                @Override
                public int getCategoryHeight() {
                    return stickyDelegate.getCategoryHeight();
                }
            });

            indexView.setDelegate(new IndexView.Delegate() {
                @Override
                public void onIndexViewSelectedChanged(IndexView indexView, String text) {
                    int position = mAdapter.getPositionForCategory(text.charAt(0));
                    if (position != -1) {
                        mRecyclerViewScrollHelper.smoothScrollToPosition(position);
                    }
                }
            });
        }else{
            mAdapter.setNewData(datas);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_cancel:
                KeyBoardUtil.closeKeybord(viewFinder.editText(R.id.search_edit), this);
                finish();
                break;
            case R.id.input_clear:
                viewFinder.editText(R.id.search_edit).setText("");
                break;

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            KeyBoardUtil.closeKeybord(viewFinder.editText(R.id.search_edit), this);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (TextUtils.isEmpty(s.toString())) {
            viewFinder.editText(R.id.search_edit).setTextAppearance(this, R.style.H4_Grey_No_Bold);
//            viewFinder.find(R.id.input_clear).setVisibility(View.GONE);
        } else {
            viewFinder.editText(R.id.search_edit).setTextAppearance(this, R.style.H4_Dark);
            //            viewFinder.find(R.id.input_clear).setVisibility(View.VISIBLE);
        }
        getPresenter().search(s.toString());
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

}
